<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <title>WebSocket 完整测试</title>
    <script src="https://cdn.jsdelivr.net/npm/sockjs-client@1.6.1/dist/sockjs.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/stompjs@2.3.3/lib/stomp.min.js"></script>
    <style>
        body {
            font-family: Arial, sans-serif;
            padding: 20px;
            max-width: 800px;
            margin: 0 auto;
            background-color: #f9f9f9;
        }

        h2 {
            color: #333;
            text-align: center;
        }

        button {
            margin: 5px;
            padding: 10px 20px;
            background-color: #007bff;
            color: white;
            border: none;
            border-radius: 5px;
            cursor: pointer;
            font-size: 14px;
        }

        button:hover {
            background-color: #0056b3;
        }

        #messages {
            margin-top: 20px;
            border: 1px solid #ccc;
            padding: 10px;
            height: 400px;
            overflow-y: scroll;
            background-color: #fff;
            border-radius: 5px;
            box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
        }

        .msg {
            margin-bottom: 8px;
            padding: 6px 10px;
            border-left: 4px solid #007bff;
            background-color: #f8f9fa;
            font-size: 14px;
            word-break: break-word;
        }

        .error {
            border-left-color: #dc3545;
            color: #721c24;
            background-color: #f8d7da;
        }

        .success {
            border-left-color: #28a745;
            color: #155724;
            background-color: #d4edda;
        }

        .info {
            border-left-color: #17a2b8;
            color: #0c5460;
            background-color: #d1ecf1;
        }
    </style>
</head>

<body>
    <!-- 按钮 -->
    <button onclick="triggerBackend()">📢 点我！让后端给我发消息</button>

    <!-- 显示消息的区域 -->
    <div id="messages"></div>
    <h2>WebSocket 测试页面（JWT 认证）</h2>

    <button onclick="sendTableStatus()">广播球台状态</button>
    <button onclick="sendReservationReminder()">广播预约提醒</button>
    <button onclick="sendSystemNotification()">广播系统通知</button>
    <button onclick="sendToUser()">发送私有消息给 user1</button>
    <button onclick="disconnect()" style="background-color: #dc3545;">断开连接</button>

    <div id="messages"></div>

    <script>
        let stompClient = null;
        // ⚠️ 仅用于测试！生产环境不应硬编码 JWT
        const jwtToken = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpbmZvcm1hdGlvbiI6eyJVc2VybmFtZSI6ImFkbWluIiwiaWQiOjF9LCJleHAiOjE3NTc4MzE4MjF9.NA8Ij-C9eucc1ucOHedzgCKBJpT_ERvI-ObfybI9j0Q";

        function logMessage(msg, type = 'info') {
            const messagesDiv = document.getElementById('messages');
            const p = document.createElement('div');
            p.className = `msg ${type}`;
            p.textContent = `[${new Date().toLocaleTimeString()}] ${msg}`;
            messagesDiv.appendChild(p);
            messagesDiv.scrollTop = messagesDiv.scrollHeight;
        }

        function connect() {
            const socket = new SockJS(`http://localhost:8099/ws?token=${jwtToken}`);
            stompClient = Stomp.over(socket);


            stompClient.connect({}, function (frame) {
                logMessage('WebSocket 连接成功: ' + frame, 'success');

                // 订阅广播球台状态
                stompClient.subscribe('/topic/table-status', function (message) {
                    logMessage('收到广播球台状态: ' + message.body, 'info');
                });

                // 订阅预约提醒
                stompClient.subscribe('/topic/reservation-reminder', function (message) {
                    logMessage('收到预约提醒: ' + message.body, 'info');
                });

                // 订阅系统通知
                stompClient.subscribe('/topic/system-notification', function (message) {
                    logMessage('收到系统通知: ' + message.body, 'success');
                });

                // 订阅私有消息（用户专属）
                stompClient.subscribe('/user/queue/table-updates', function (message) {
                    logMessage('收到私有消息: ' + message.body, 'info');
                }, function (error) {
                    logMessage('订阅私有消息失败: ' + error, 'error');
                });

            }, function (error) {
                logMessage('WebSocket 连接失败: ' + error, 'error');
            });
        }

        function disconnect() {
            if (stompClient !== null) {
                stompClient.disconnect();
                logMessage("已断开连接", 'success');
            }
        }

        function sendTableStatus() {
            if (stompClient === null) return alert("请先连接！");
            stompClient.send('/app/sendTableStatus', {}, '1'); // 发送 tableId=1
            logMessage('已发送【广播球台状态】请求', 'info');
        }

        function sendReservationReminder() {
            if (stompClient === null) return alert("请先连接！");
            stompClient.send('/app/sendReservationReminder', {}, '您有新的预约提醒！');
            logMessage('已发送【广播预约提醒】请求', 'info');
        }

        function sendSystemNotification() {
            if (stompClient === null) return alert("请先连接！");
            stompClient.send('/app/sendSystemNotification', {}, '系统通知：服务器运行正常！');
            logMessage('已发送【广播系统通知】请求', 'info');
        }

        function sendToUser() {
            if (stompClient === null) return alert("请先连接！");
            const payload = JSON.stringify({
                username: 'user1',
                payload: '这是发给 user1 的私有消息 @ ' + new Date().toLocaleTimeString()
            });
            stompClient.send('/app/sendToUser', {}, payload);
            logMessage('已发送【私有消息】给 user1', 'info');
        }

        // 页面加载时自动连接
        window.onload = function () {
            connect();
        };

    </script>

</body>

</html>
